

#include "CMPS03.h"
#include "RP6I2CmasterTWI.h"
#include <stdbool.h>

uint16_t cmps03_currentDirection=0;
uint8_t cmps03_isInitialized=false;
uint8_t cmps03_isMeasuring = false;


void CMPS03_measure(void)
{
	if(!cmps03_isMeasuring)
	{
		if(TWI_operation == I2CTWI_NO_OPERATION)
		{
			I2CTWI_requestRegisterFromDevice(CMPS03_ADDRESS, CMPS03_DIR, 2,2);
			cmps03_isMeasuring = true;
		}
	}
}

uint8_t CMPS03_init(void){
	uint8_t buf[1];
	while(I2CTWI_isBusy()){
		mSleep(1);
	}
	I2CTWI_readRegisters(CMPS03_ADDRESS,0,buf,1);
	if(buf[0]!=CMPS03_FIRMWARE){
		cmps03_isInitialized=false;
	}else{
		cmps03_isInitialized=true;
	}
	return cmps03_isInitialized;
}	

void CMPS03_onDataReady( uint8_t dataRequestID )
{
	uint8_t messageBuf[8];
	switch(dataRequestID)
	{
		case CMPS03_DIR:
		{
			I2CTWI_getReceivedData(messageBuf, 2);
			cmps03_currentDirection = messageBuf[1] + (messageBuf[0] << 8);
			cmps03_isMeasuring=false;
			break;
		}			
	}
}	

uint16_t *CMPS03_getDirection(){
	return &cmps03_currentDirection;
}
uint8_t CMPS03_isInitialized(void)
{
	return cmps03_isInitialized;
}